﻿namespace VehicleRental.API.Controllers
{
    using System;
    using System.Data.Entity.Validation;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Text;
    using System.Web.Http;
    using VehicleRental.Data;
    using VehicleRental.Models;

    public class BaseApiController : ApiController
    {
        protected static Random rand = new Random();

        protected T ExecuteOperationAndHandleExceptions<T>(Func<T> operation)
        {
            try
            {
                return operation();
            }
            catch (DbEntityValidationException dbEx)
            {
                StringBuilder errorBuilder = new StringBuilder();

                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errorBuilder.AppendFormat("Property: {0} Error: {1}\n\r", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }

                var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, errorBuilder.ToString());
                throw new HttpResponseException(errResponse);
            }
            catch (InvalidOperationException ex)
            {
                var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
                throw new HttpResponseException(errResponse);
            }
            catch (Exception ex)
            {
                var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
                throw new HttpResponseException(errResponse);
            }
        }

        protected User GetUserByAccessToken(string accessToken, VehicleRentalContext context)
        {
            User user = context.Users.FirstOrDefault(usr => usr.AccessToken == accessToken);
            if (user == null)
            {
                throw new InvalidOperationException("Invalid user credentials");
            }
            return user;
        }
    }
}
